// Copyright 2010 Google Inc. All Rights Reserved.

package com.google.zahra.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * @author arthurkok@google.com (Your Name Here)
 *
 */
public class Util {

  private static String cssStyle;

  public static String stackTraceToString(Throwable e) {
    String retValue = null;
    StringWriter sw = null;
    PrintWriter pw = null;
    try {
      sw = new StringWriter();
      pw = new PrintWriter(sw);
      e.printStackTrace(pw);
      retValue = sw.toString();
    } finally {
      try {
        if (pw != null) pw.close();
        if (sw != null) sw.close();
      } catch (IOException ignore) {
      }
    }
    return retValue;
  }

  public static String getOsName(int os) {
    switch (os) {
      case 1:
        return "WINDOWS";
      case 2:
        return "MAC";
      case 4:
        return "UNIX";
      default:
        return "NOT AN OS!";
    }
  }

  public static String getHTML(String body, String title) {

    // if (cssStyle == null) {
    File file = new File(System.getProperty("user.dir") + "/zahra/style.css");
    StringBuffer contents = new StringBuffer();
    BufferedReader reader = null;

    try {
      reader = new BufferedReader(new FileReader(file));
      String text = null;

      // repeat until all lines is read
      while ((text = reader.readLine()) != null) {
        contents.append(text);
      }

      cssStyle = contents.toString();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        if (reader != null) {
          reader.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    // }

    StringBuffer html = new StringBuffer();
    html.append("<html>");
    html.append("<head><title>" + title + "</title>");
    html.append("<style type='text/css'>" + cssStyle + "</style></head>");
    html.append("<body><div id='container'>");
    html.append("<a href='/'><< Go Home</a><br/><br/>");
    html.append("<img src='http://www.google.com/images/logos/ps_logo.png'/>");
    html.append("<div id='title'>Zahra</div>");
    html.append("<h1>Welcome to Zahra!</h1>");
    // bodyString.append("session=" +
    // request.getSession(true).getId());
    html.append(body + "</div></body>");

    html.append("</html>");
    return html.toString();
  }
}
